<?php
namespace app\admin\controller;

use think\Db;
use think\Request;
class UserRole extends Common
{

    /**
     * 列表
     */
    public function index(){
        if(Request::instance()->isAjax()){
            $input = array_filter(input('','','trim'));
            $input['type'] = session('user.type');
            return \app\common\model\UserRole::getList($input);
        }
        return view('');
    }


    /**
     * 创建
     */
    public function create(){
        $this->view->engine->layout('common/iframe');
        return view('');
    }


    /**
     * 编辑
     */
    public function edit(){
        try{
            $this->view->engine->layout('common/iframe');
            $id = input('id');
            $role = \app\common\model\UserRole::get($id);
            if(empty($role)){
                exception('角色信息不存在');
            }
            return view('create',['role'=>$role]);
        }catch (\Exception $e) {
            return view('common/error',['msg' => $e->getMessage()]);
        }
    }


    /**
     * 删除
     */
    public function delete(){
        try{
            $id = input('id');
            $user = \app\common\model\User::where(['role_id'=>$id])->select();
            if(!empty($user)){
                exception('存在用户使用该角色,不可删除');
            }
            $role = \app\common\model\UserRole::destroy($id);
            if ($role){
                return ['code'=>'0','msg'=>'删除成功'];
            }else{
                return ['code'=>'1','msg'=>'删除成功'];
            }
        }catch (\Exception $exception) {
            return json(['code' => 1, 'msg' => $exception->getMessage(), 'data' => []]);
        }
    }


    /**
     * 权限列表
     */
    public function menuList()
    {
        try {
            $roleArray = [];
            $role_id = input('roleId');

            if($role_id){
                $roleInfo = \app\common\model\UserRole::where(['id'=>$role_id])->column('menu_ids');
                $roleArray = explode(",",$roleInfo[0]);
            }

            $con = [
                'model'=>'admin',
                'is_show'=>1,
            ];

            $role_id = session('user.role_id');

            if($role_id != 1){
                $user_role = \app\common\model\UserRole::get(['id'=>session('user.role_id')]);
                $con['id'] = ['in',explode(',',$user_role['menu_ids'])];
            }

            $menu = Db::name('user_menu')->where($con)->field('id,name as text,level,parent_id,url')->order(['sort'=>'desc'])->select();
            $parent_array = array_column($menu,'parent_id');

            if($role_id != -1){
                foreach ($menu as $k => $v){
                    if(in_array($v['id'],$roleArray) && !in_array($v['id'],$parent_array)){
                        $menu[$k]['state'] = ['selected'=>true];
                    }
                }
            }
            $tree = list_to_tree($menu, 'id', 'parent_id', 'children');
            return json($tree);
        } catch (\Exception $exception) {
            return json(['code' => 0, 'msg' => $exception->getMessage()]);
        }
    }



    /**
     * 保存
     */
    public function save(){
        try{
            $data = input('post.','','trim');

            $validate = $this->validate($data, 'UserRole');
            if ($validate !== true) {
                exception($validate);
            }

            $data['menu_ids'] = implode(',',$data['menu_ids']);

            Db::startTrans();
            if(isset($data['id']) && !empty($data['id'])){
                $role = \app\common\model\UserRole::get(['id'=>$data['id']]);
                if($role->force()->update($data) === false){
                    exception('保存失败');
                }
            }else{
                $role = new \app\common\model\UserRole($data);
                $data['user_id'] = $this->userId;
                if(!$role->force()->save($data)){
                    exception('保存失败');
                }
            }
            Db::commit();
            return  json(['code'=>0,'msg'=>'操作成功']);
        } catch (\Exception $e) {
            Db::rollback();
            return json(['code' => 1, 'msg' => $e->getMessage(), 'data' => []]);
        }

    }

}
